package newsletterService

import (
	"context"
	"encoding/json"
	"github.com/Sir-yuChen/funAnalyse/global"
	"github.com/Sir-yuChen/funAnalyse/global/constant"
	mqConstant "github.com/Sir-yuChen/funAnalyse/global/mq"
	"github.com/Sir-yuChen/funAnalyse/model"
	"github.com/Sir-yuChen/funAnalyse/model/common/ApiReturn"
	"github.com/Sir-yuChen/funAnalyse/model/request"
	"github.com/Sir-yuChen/funAnalyse/service/basisService"
	"github.com/Sir-yuChen/funAnalyse/service/commonService"
	"github.com/Sir-yuChen/funAnalyse/utils/kafka"
	"github.com/Sir-yuChen/funAnalyse/utils/mongodb"
	"github.com/Sir-yuChen/funAnalyse/utils/rabbitMq"
	"github.com/Sir-yuChen/funAnalyse/utils/socket"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/bson"
	"go.uber.org/zap"
	"strings"
	"time"
)

type CommunicationService struct{}

/* 聊天室流程：
1. 用户必须注册登录
2. 调用创建长连接接口 CreateWebsocket 创建用户的长连接，当用户点击通讯页面时，前端就应调用该接口创建
3. 需要聊天就必须是好友，首先发送好友请求AddCommunicationFriend，对方同意好友请求AddFriend，成为好友
4. 此时可以获取用户通讯录，已查看，两个账户好友关系及信息
5. 开始聊天，首先创建聊天室，群聊和单独聊天室
6. 聊天室创建完成，发送消息,未在线消息状态则是未读取状态，用户上线后可通过调用读取消息接口进行获取，读取通讯录会自动读取聊天室未读的消息

*/

// CreateChatroom 1. 创建聊天室
func (w *CommunicationService) CreateChatroom(c *gin.Context, req *request.CreateChatroomRequest) ApiReturn.ApiReturnCode {
	flg := false
	ok := ApiReturn.OK
	ctx := context.TODO()
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("创建房间,获取当前账户信息异常", zap.Any("request", req), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	uid, _ := uuid.NewUUID()
	roomId := strings.Replace(uid.String(), "-", "", -1)
	recipientCustomerIds := strings.Split(req.RecipientCustomerId, ",")
	recipientCustomerIds = append(recipientCustomerIds, user.CustomerId)
	var roomMenbers []model.RoomMenber
	baseRoom := model.BaseRoom{
		RoomId:     roomId,
		RoomType:   req.Type,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}
	for _, uid := range recipientCustomerIds {
		roomMenber := model.RoomMenber{
			RoomId:     roomId,
			CustomerId: uid,
			Status:     constant.STATUS_Y,
			Identity:   constant.CHAT_MEMBER_Identity_ordinary,
			CreateTime: time.Now().Format("2006-01-02 15:04:05"),
		}
		if uid == user.CustomerId {
			roomMenber.Identity = constant.CHAT_MEMBER_Identity_creator
		}
		roomMenbers = append(roomMenbers, roomMenber)
	}
	roomOnUser := model.RoomOnUser{
		RoomId:        baseRoom.RoomId,
		CustomerId:    user.CustomerId,
		Status:        constant.STATUS_Y,
		BackgroundImg: "https://s.cn.bing.net/th?id=OHR.GeorgiaCypress_ZH-CN3705257154_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&qlt=50",
		CreateTime:    time.Now().Format("2006-01-02 15:04:05"),
	}
	//根据类型添加参数
	switch req.Type {
	case constant.CHAT_ROOM_TYPE_single: //一对一
		//校验私聊只能一个接收者
		if len(recipientCustomerIds) > 2 {
			global.GVA_LOG.Warn("多个接收者无法创建私聊", zap.Any("request", req), zap.Error(err))
			apireturn := ApiReturn.OK
			apireturn.Msg = "请创建群聊"
			return apireturn
		}
		//验证是否是好友
		count, err := mongodb.CommunicationUserCollection.SelectCount(ctx, bson.M{
			"customerid":       user.CustomerId,
			"friendcustomerid": req.RecipientCustomerId,
		})
		if count <= 0 {
			global.GVA_LOG.Warn("不是好友关系，无法创建私聊", zap.Any("request", req), zap.Error(err))
			apireturn := ApiReturn.OK
			apireturn.Msg = "非好友,无法创建私聊,请先添加好友"
			return apireturn
		}
		//校验是否已经存在过聊天室
		filter := bson.M{
			"customerid":          user.CustomerId,
			"recipientcustomerid": recipientCustomerIds[0],
		}
		//查当前用户下所有的聊天室，是否已经存在与接收人相同的聊天室，存在着返回已存在的信息
		single, _ := mongodb.CommunicationSingleUserCollection.SelectOne(ctx, filter)
		if single == nil {
			filter := bson.M{
				"recipientcustomerid": user.CustomerId,
				"customerid":          recipientCustomerIds[0],
			}
			single, _ = mongodb.CommunicationSingleUserCollection.SelectOne(ctx, filter)
		}
		if single != nil {
			var mo model.SingleRoomUser
			bytes, err := bson.Marshal(single)
			if err != nil {
				global.GVA_LOG.Error("数据转换异常", zap.Any("request", req), zap.Error(err))
				return ApiReturn.ErrSystem
			}
			bson.Unmarshal(bytes, &mo)
			roomFilter := bson.M{
				"roomid":     mo.RoomId,
				"customerid": recipientCustomerIds[0],
			}
			//私聊房间已经存在
			selectOne, err := mongodb.CommunicationUserRoomCollection.SelectOne(ctx, roomFilter)
			if selectOne != nil {
				var m model.RoomOnUser
				bas, err := bson.Marshal(selectOne)
				if err != nil {
					global.GVA_LOG.Error("数据转换异常", zap.Any("request", req), zap.Error(err))
					return ApiReturn.ErrSystem
				}
				bson.Unmarshal(bas, &m)
				if m.Status != constant.STATUS_Y {
					m.Status = constant.STATUS_Y
					_, err := mongodb.CommunicationRoomCollection.UpdateOne(ctx, roomFilter, m)
					if err != nil {
						global.GVA_LOG.Error("修改房间状态", zap.Any("roomInfo", m), zap.Error(err))
						return ApiReturn.ErrSystem
					}
				}
				basisRoomFilter := bson.M{
					"roomid": mo.RoomId,
				}
				bRoom, err := mongodb.CommunicationRoomCollection.SelectOne(ctx, basisRoomFilter)
				if bRoom != nil {
					var bm model.BaseRoom
					b, err := bson.Marshal(bRoom)
					if err != nil {
						global.GVA_LOG.Error("数据转换异常", zap.Any("request", req), zap.Error(err))
						return ApiReturn.ErrSystem
					}
					bson.Unmarshal(b, &bm)
					baseRoom = bm
				}
				flg = true
			}
		}
		if !flg {
			//对方用户名
			info, err := basisService.NewUserService().GetUserInfo(recipientCustomerIds[0])
			if err != nil {
				global.GVA_LOG.Error("创建房间,查用户名异常", zap.Any("request", req), zap.Error(err))
				return ApiReturn.ErrSystem
			}
			roomOnUser.RoomName = info.CustomerName
			recipientRoomOnUser := model.RoomOnUser{
				RoomId:        baseRoom.RoomId,
				CustomerId:    recipientCustomerIds[0],
				Status:        constant.STATUS_Y,
				BackgroundImg: "https://s.cn.bing.net/th?id=OHR.GeorgiaCypress_ZH-CN3705257154_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&qlt=50",
				RoomName:      user.CustomerName,
				CreateTime:    time.Now().Format("2006-01-02 15:04:05"),
			}
			if id, err := mongodb.CommunicationUserRoomCollection.InsetOne(ctx, recipientRoomOnUser); err != nil {
				global.GVA_LOG.Error("创建房间异常,一对一", zap.Any("request", req), zap.Any("id", id), zap.Error(err))
				return ApiReturn.ErrSystem
			}
			singleRoomUser := model.SingleRoomUser{
				RoomId:              baseRoom.RoomId,
				CustomerId:          user.CustomerId,
				RecipientCustomerId: recipientCustomerIds[0],
				CreateTime:          time.Now().Format("2006-01-02 15:04:05"),
			}
			if id, err := mongodb.CommunicationSingleUserCollection.InsetOne(ctx, singleRoomUser); err != nil {
				global.GVA_LOG.Error("创建房间异常,一对一", zap.Any("request", req), zap.Any("id", id), zap.Error(err))
				return ApiReturn.ErrSystem
			}
		}
		break
	case constant.CHAT_ROOM_TYPE_crowd: //多人
		var lists []interface{}
		roomNames := ""
		for i, recipientCustomerId := range recipientCustomerIds {
			if i < 5 {
				//对方用户名
				info, err := basisService.NewUserService().GetUserInfo(recipientCustomerId)
				if err != nil {
					global.GVA_LOG.Error("创建房间,多人,查用户名异常", zap.Any("request", req), zap.Error(err))
				}
				//生成群聊名
				roomNames += info.CustomerName
			}
		}
		for _, item := range recipientCustomerIds {
			recipientRoomOnUser := model.RoomOnUser{
				RoomId:        baseRoom.RoomId,
				CustomerId:    item,
				Status:        constant.STATUS_Y,
				BackgroundImg: "https://s.cn.bing.net/th?id=OHR.GeorgiaCypress_ZH-CN3705257154_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&qlt=50",
				RoomName:      roomNames,
				CreateTime:    time.Now().Format("2006-01-02 15:04:05"),
			}
			lists = append(lists, recipientRoomOnUser)
		}
		roomOnUser.RoomName = roomNames
		if ids, err := mongodb.CommunicationUserRoomCollection.InsertMany(ctx, lists); err != nil {
			global.GVA_LOG.Error("创建房间异常,群聊", zap.Any("request", req), zap.Any("ids", ids), zap.Error(err))
			return ApiReturn.ErrSystem
		}
		break
	default:
		global.GVA_LOG.Error("未知的房间类型", zap.Any("request", req))
		apireturn := ApiReturn.OK
		apireturn.Msg = "未知的房间类型"
		return apireturn
	}
	if !flg {
		//将房间信息入库
		if id, err := mongodb.CommunicationRoomCollection.InsetOne(ctx, baseRoom); err != nil {
			global.GVA_LOG.Error("创建房间异常", zap.Any("request", req), zap.Any("id", id), zap.Error(err))
			return ApiReturn.ErrSystem
		}
		for _, menber := range roomMenbers {
			if id, err := mongodb.CommunicationRoomMemberCollection.InsetOne(ctx, menber); err != nil {
				global.GVA_LOG.Error("新增聊天室成员异常", zap.Any("menber", menber), zap.Any("id", id), zap.Error(err))
				continue
			}
		}
		if id, err := mongodb.CommunicationUserRoomCollection.InsetOne(ctx, roomOnUser); err != nil {
			global.GVA_LOG.Error("创建房间异常", zap.Any("request", req), zap.Any("id", id), zap.Error(err))
			return ApiReturn.ErrSystem
		}
	}
	re := map[string]interface{}{}
	re["baseRoom"] = baseRoom
	re["userRoom"] = roomOnUser
	ok.Data = re
	return ok
}

// SendCommunicationMsg 发送消息
func (w *CommunicationService) SendCommunicationMsg(c *gin.Context, req *request.SendMessageRequest) (apireturn ApiReturn.ApiReturnCode) {
	/*
		1. 用户发送消息，后端接收，解析，将消息放kafka中处理
		2. kafka消费消息，校验用户是否在线，用户不在线，则将消息状态设置为未取取状态，在线，将消息写入用户长连接，并设置为已读状态
	*/
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账号信息异常", zap.Error(err))
		return ApiReturn.Failure
	}
	ctx := context.TODO()
	//聊天室是否存在
	filter := bson.M{
		"roomid": req.RoomId,
	}
	count, err := mongodb.CommunicationRoomCollection.SelectCount(ctx, filter)
	if err != nil {
		global.GVA_LOG.Error("聊天室是否存在异常", zap.Any("request", req), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	if count == 0 {
		apireturn = ApiReturn.ErrSystem
		apireturn.Msg = "聊天室不合法"
		return apireturn
	}
	uid, _ := uuid.NewUUID()
	msgId := strings.Replace(uid.String(), "-", "", -1)
	baseInformation := model.BaseInformation{
		RoomId:             req.RoomId,
		InformationId:      msgId,
		InformationType:    req.Type,
		InformationContent: req.Content,
		Despatcher:         user.CustomerId,
		Sequence:           1,
		CreateTime:         time.Now().Format("2006-01-02 15:04:05"),
	}
	informationSender := model.InformationOnUser{
		CustomerId:        user.CustomerId,
		InformationId:     msgId,
		UserIdentity:      constant.MSG_User_Identity_sender,
		InformationStatus: constant.MSG_STATUS_WILL_processed,
		CreateTime:        time.Now().Format("2006-01-02 15:04:05"),
	}
	completeInformation := model.CompleteInformation{
		BaseInfo:          baseInformation,
		InformationSender: informationSender,
	}
	//kafka 发送消息
	producer, err := kafka.GetKafkaProducer(global.GVA_CONFIG.KafkaConfig.Link)
	if err != nil {
		global.GVA_LOG.Error("创建kafka连接异常", zap.Error(err))
		return ApiReturn.ErrSystem
	}
	defer func() {
		if err = producer.Close(); err != nil {
			global.GVA_LOG.Error(" close kafka producer err!", zap.Error(err))
		}
	}()
	jsonStr, err := json.Marshal(completeInformation)
	if err != nil {
		global.GVA_LOG.Error("数据转换异常", zap.Any("completeInformation", completeInformation), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	err = kafka.SendMsgToKafka(producer, mqConstant.MQ_KAFKA_CHAT_MSG, mqConstant.MQ_KAFKA_CHAT_MSG_KEY, string(jsonStr), 1)
	if err != nil {
		global.GVA_LOG.Error("kafka消息投递异常", zap.Any("completeInformation", completeInformation), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	return ApiReturn.OK
}

// ReadChatroomMsg  读取聊天室消息
func (w *CommunicationService) ReadChatroomMsg(req *request.ReadMessageRequest, c *gin.Context) ApiReturn.ApiReturnCode {
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账户信息异常", zap.Any("customerId", user.CustomerId), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	client := socket.GetClient(user.CustomerId)
	//msgData := map[string]interface{}{}
	for _, c := range client {
		c.Read()
	}
	ctx := context.TODO()
	//根据用户ID和消息状态，查information_on_user 获取所有的消息ID
	filter := bson.M{
		"customerid":        user.CustomerId,
		"informationstatus": constant.MSG_STATUS_WILL_processed,
	}
	informationOnUserList, err := mongodb.CommInformationOnUserCollection.SelectList(ctx, filter, nil)
	if err != nil {
		global.GVA_LOG.Error("获取所有未读消息ID", zap.Any("request", req), zap.Any("customerId", user.CustomerId), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	informationOnUsers := []*model.InformationOnUser{}
	for _, item := range informationOnUserList {
		app := new(model.InformationOnUser)
		bytes, err := bson.Marshal(item)
		if err != nil {
			global.GVA_LOG.Error("Mongdb 查询集合数据转换异常", zap.Any("jsonStr", item), zap.Error(err))
		}
		bson.Unmarshal(bytes, app)
		informationOnUsers = append(informationOnUsers, app)
	}
	/* todo 消息未读状态
	for _, informationOnUser := range informationOnUsers {

	}
	*/

	return ApiReturn.OK
}

// CreateWebsocket 创建用户聊天长连接
func (w *CommunicationService) CreateWebsocket(c *gin.Context) ApiReturn.ApiReturnCode {
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账户信息异常", zap.Any("customerId", user.CustomerId), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	//校验重复创建
	clients := socket.GetClient(user.CustomerId)
	if len(clients) > 0 {
		for _, client := range clients {
			if client.CustomerId == user.CustomerId {
				global.GVA_LOG.Warn("用户长连接已经存在，请不要重复创建！！！", zap.Any("customerId", user.CustomerId))
				return ApiReturn.OK
			}
		}
	}
	//创建长连接
	if err := socket.CreateWebSocketConnection(user.CustomerId, global.ChatStock, c); err != nil {
		global.GVA_LOG.Error("用户创建长连接异常", zap.Error(err))
		return ApiReturn.ErrSystem
	}
	return ApiReturn.OK
}

// GetCommunicationBasis  获取用户通讯录，用户拥有的聊天室
func (w *CommunicationService) GetCommunicationBasis(c *gin.Context) (apireturn ApiReturn.ApiReturnCode) {
	ctx := context.TODO()
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账户信息异常", zap.Error(err))
		return ApiReturn.ErrSystem
	}
	filter := bson.M{
		"customerid": user.CustomerId,
		"status":     "Y",
	}
	friendlist, err := mongodb.CommunicationUserCollection.SelectList(ctx, filter, nil)
	if err != nil {
		global.GVA_LOG.Error("获取用户通讯录异常", zap.Any("request", user.CustomerId), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	friends := []*model.CommunicationFriends{}
	for _, item := range friendlist {
		app := new(model.CommunicationFriends)
		bytes, err := bson.Marshal(item)
		if err != nil {
			global.GVA_LOG.Error("Mongdb 查询集合数据转换异常", zap.Any("jsonStr", item), zap.Error(err))
		}
		bson.Unmarshal(bytes, app)
		friends = append(friends, app)
	}
	//用户拥有的聊天室
	roomList, err := mongodb.CommunicationUserRoomCollection.SelectList(ctx, filter, nil)
	if err != nil {
		global.GVA_LOG.Error("获取当前用户所有的聊天室", zap.Any("request", user.CustomerId), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	rooms := []*model.RoomOnUser{}
	for _, item := range roomList {
		room := new(model.RoomOnUser)
		bytes, err := bson.Marshal(item)
		if err != nil {
			global.GVA_LOG.Error("Mongdb 查询集合数据转换异常", zap.Any("jsonStr", item), zap.Error(err))
		}
		bson.Unmarshal(bytes, room)
		rooms = append(rooms, room)
	}
	apireturn.Data = map[string]interface{}{
		"userFriends": friends,
		"userRooms":   rooms,
	}
	return apireturn
}

// AddCommunicationFriend 添加好友请求【仅仅是好友请求】
func (w *CommunicationService) AddCommunicationFriend(c *gin.Context, req *request.AddCommunicationFriendRequest) (apireturn ApiReturn.ApiReturnCode) {
	/*
		1. 发送请求，携带参数，校验用户状态是否正常，校验是否已经是好友
		2. 放MQ作为消息处理，消息类型为添加好友，写入长连接，用户登录则提醒，显示统一忽略按钮
		3. 同意，修改已落Mongodb的数据类型，并新增好友关系，忽略则修改消息状态即可
	*/
	ctx := context.TODO()
	apireturn = ApiReturn.OK
	info, err := basisService.NewUserService().GetUserInfo(req.FriendCustomerId)
	if err != nil {
		global.GVA_LOG.Error("校验添加的好友用户状态异常", zap.Any("request", req), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	if info.Status != constant.STATUS_Y {
		global.GVA_LOG.Error("校验添加的好友用户状态不正常，不能添加好友", zap.Any("request", req), zap.Error(err))
		apireturn.Msg = "对方账号不正常，不能添加好友"
		return apireturn
	}
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账号信息异常", zap.Error(err))
		return ApiReturn.ErrSystem
	}
	filter := bson.M{
		"customerid":       user.CustomerId,
		"friendcustomerid": req.FriendCustomerId,
	}
	count, err := mongodb.CommunicationUserCollection.SelectCount(ctx, filter)
	if count >= 1 {
		global.GVA_LOG.Warn("已经是好友关系", zap.Any("request", req), zap.Error(err))
		apireturn.Msg = "已经是好友关系,请不要重复添加"
		return apireturn
	}
	//kafka 发送消息
	jsonStr, err := json.Marshal(req)
	if err != nil {
		global.GVA_LOG.Error(" 数据转换异常", zap.Any("request", req), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	uid, _ := uuid.NewUUID()
	msgId := strings.Replace(uid.String(), "-", "", -1)
	baseInformation := model.BaseInformation{
		InformationId:      msgId,
		InformationType:    constant.MSG_TYPE_friend,
		InformationContent: string(jsonStr),
		Despatcher:         user.CustomerId,
		Sequence:           0,
	}
	if _, err := mongodb.CommunicationBaseInformationCollection.InsetOne(ctx, baseInformation); err != nil {
		global.GVA_LOG.Error("新增基础消息记录异常", zap.Any("request", req), zap.Any("baseInformation", baseInformation), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	informationSender := model.InformationOnUser{
		CustomerId:        user.CustomerId,
		InformationId:     msgId,
		UserIdentity:      constant.MSG_User_Identity_sender,
		InformationStatus: constant.MSG_STATUS_WILL_processed,
		CreateTime:        time.Now().Format("2006-01-02 15:04:05"),
	}
	informationRecipient := model.InformationOnUser{
		CustomerId:        req.FriendCustomerId,
		InformationId:     msgId,
		UserIdentity:      constant.MSG_User_Identity_recipient,
		InformationStatus: constant.MSG_STATUS_WILL_processed,
		CreateTime:        time.Now().Format("2006-01-02 15:04:05"),
	}
	//rabbitMq处理消息
	listInfo := []model.InformationOnUser{
		informationSender, informationRecipient,
	}
	chatQueueExchange := rabbitMq.QueueExchange{
		QuName: mqConstant.MQ_QUEUE_CHAT,
		RtKey:  mqConstant.MQ_ROUTING_KEY_CHAT_1,
		ExName: mqConstant.MQ_EXCHANG,
		ExType: mqConstant.MQ_EX_TYPE_direct,
	}
	jstr, err := json.Marshal(listInfo)
	if err != nil {
		global.GVA_LOG.Error(" 数据转换异常", zap.Any("Msg", jstr), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	rabbitMq.Send(chatQueueExchange, string(jstr))
	apireturn = ApiReturn.OK
	return apireturn
}

// AddFriend  好友申请处理
func (w *CommunicationService) AddFriend(c *gin.Context, req *request.AddFriendRequest) (apireturn ApiReturn.ApiReturnCode) {
	/*
		处理用户好友请求：
				同意，修改已落Mongodb的数据类型，并新增好友关系，忽略则修改消息状态即可
	*/
	ctx := context.TODO()
	filter := bson.M{
		"informationid": req.MessageId,
	}
	selectOne, err := mongodb.CommunicationBaseInformationCollection.SelectOne(ctx, filter)
	if err != nil {
		global.GVA_LOG.Error("查消息的基础信息异常", zap.Any("request", req), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	var baseInformation model.BaseInformation
	var areq request.AddCommunicationFriendRequest
	if selectOne != nil {
		bas, err := bson.Marshal(selectOne)
		err = bson.Unmarshal(bas, &baseInformation)
		json.Unmarshal([]byte(baseInformation.InformationContent), &areq)
		if err != nil {
			global.GVA_LOG.Error("数据转换异常", zap.Any("baseInformation", baseInformation), zap.Error(err))
			return ApiReturn.ErrSystem
		}
	}
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账号信息异常", zap.Error(err))
		return ApiReturn.ErrSystem
	}
	//以请求着的角度
	askAddFriendmsg := model.CommunicationFriends{
		CustomerId:       baseInformation.Despatcher,
		FriendCustomerId: user.CustomerId,
		RemarkFriendName: areq.RemarkFriendName,
		FriendType:       areq.FriendType,
		Source:           areq.Source,
		CreateTime:       time.Now().Format("2006-01-02 15:04:05"),
	}
	//以被请求添加好友的角度
	requestedAddFriendmsg := model.CommunicationFriends{
		CustomerId:       user.CustomerId,
		FriendCustomerId: baseInformation.Despatcher,
		RemarkFriendName: req.RemarkFriendName,
		FriendType:       req.FriendType,
		Source:           req.Source,
		CreateTime:       time.Now().Format("2006-01-02 15:04:05"),
	}
	if req.Status == constant.FRIEND_Ask_agree {
		askAddFriendmsg.Status = constant.User_Friend_Y
		requestedAddFriendmsg.Status = constant.User_Friend_Y
	} else {
		askAddFriendmsg.Status = constant.User_Friend_NT
		requestedAddFriendmsg.Status = constant.User_Friend_NT
	}
	if _, err := mongodb.CommunicationUserCollection.InsetOne(ctx, askAddFriendmsg); err != nil {
		global.GVA_LOG.Error("新增通讯录异常", zap.Any("askAddFriendmsg", askAddFriendmsg), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	if _, err := mongodb.CommunicationUserCollection.InsetOne(ctx, requestedAddFriendmsg); err != nil {
		global.GVA_LOG.Error("新增通讯录异常", zap.Any("requestedAddFriendmsg", requestedAddFriendmsg), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	update := bson.D{{"$set",
		bson.D{
			{"informationstatus", constant.MSG_STATUS_WILL_Processe_success},
		},
	}}
	updateFilter := bson.M{"customerid": user.CustomerId, "informationid": baseInformation.InformationId}
	if _, err := mongodb.CommInformationOnUserCollection.UpdateOne(ctx, updateFilter, update); err != nil {
		global.GVA_LOG.Error("修改消息状态异常", zap.Any("baseInformation", baseInformation), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	//todo 处理完请求后，应发送MQ消息告诉用户处理结果
	apireturn = ApiReturn.OK
	return apireturn
}

// UpdateFriendInfo 修改好友关系信息
func (w *CommunicationService) UpdateFriendInfo(req *request.UpdateFriendInfoRequest, c *gin.Context) (apireturn ApiReturn.ApiReturnCode) {
	//确认是否是好友关系
	ctx := context.TODO()
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账户信息异常", zap.Any("request", req), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	count, err := mongodb.CommunicationUserCollection.SelectCount(ctx, bson.M{
		"customerid":       user.CustomerId,
		"friendcustomerid": req.FriendCustomerId,
	})
	if count <= 0 {
		global.GVA_LOG.Warn("非好友关系", zap.Any("request", req), zap.Error(err))
		apireturn = ApiReturn.OK
		apireturn.Msg = "非好友关系"
		return apireturn
	}
	m := map[string]interface{}{}
	j, _ := json.Marshal(req)
	err = json.Unmarshal(j, &m)
	if err != nil {
		global.GVA_LOG.Warn("数据转换异常", zap.Any("request", req), zap.Error(err))
		apireturn = ApiReturn.ErrSystem
		return apireturn
	}
	var setElements bson.D
	for key, value := range m {
		if value != "" {
			setElements = append(setElements, bson.E{key, value})
		}
	}
	//是好友这修改
	update := bson.D{{"$set", setElements}}
	filter := bson.M{"customerid": user.CustomerId, "friendcustomerid": req.FriendCustomerId}
	if _, err := mongodb.CommInformationOnUserCollection.UpdateOne(ctx, filter, update); err != nil {
		global.GVA_LOG.Error("修改好友信息异常", zap.Any("request", req), zap.Error(err))
		apireturn = ApiReturn.ErrSystem
		return apireturn
	}
	apireturn = ApiReturn.OK
	return apireturn
}

// UpdateBasisRoomInfo 修改聊天室信息
func (w *CommunicationService) UpdateBasisRoomInfo(req *request.UpdateBasisRoomInfoRequest, c *gin.Context) (apireturn ApiReturn.ApiReturnCode) {
	ctx := context.TODO()
	user, err := commonService.GetUserInfoByToken(c)
	if err != nil {
		global.GVA_LOG.Error("获取当前账户信息异常", zap.Any("request", req), zap.Error(err))
		return ApiReturn.ErrSystem
	}
	userRoom, err := mongodb.CommunicationUserRoomCollection.SelectOne(ctx, bson.M{
		"customerid": user.CustomerId,
		"roomid":     req.RoomId,
	})
	if userRoom == nil {
		global.GVA_LOG.Warn("用户不存在当前房间信息", zap.Any("request", req), zap.Error(err))
		apireturn = ApiReturn.OK
		apireturn.Msg = "用户不存在当前房间信息"
		return apireturn
	}
	m := map[string]interface{}{}
	j, _ := json.Marshal(req)
	err = json.Unmarshal(j, &m)
	if err != nil {
		global.GVA_LOG.Warn("数据转换异常", zap.Any("request", req), zap.Error(err))
		apireturn = ApiReturn.ErrSystem
		return apireturn
	}
	var setElements bson.D
	for key, value := range m {
		if value != "" {
			setElements = append(setElements, bson.E{key, value})
		}
	}
	update := bson.D{{"$set", setElements}}
	filter := bson.M{"customerid": user.CustomerId, "roomid": req.RoomId}
	if _, err := mongodb.CommInformationOnUserCollection.UpdateOne(ctx, filter, update); err != nil {
		global.GVA_LOG.Error("修改用户聊天室信息异常", zap.Any("request", req), zap.Error(err))
		apireturn = ApiReturn.ErrSystem
		return apireturn
	}
	//修改聊天室成员状态 如果为 true，则表明 key 存在，否则 key 不存在。
	if v, isOk := m["status"]; isOk {
		memberInfo, err := mongodb.CommunicationRoomMemberCollection.SelectOne(ctx, bson.M{
			"customerid": user.CustomerId,
			"roomid":     req.RoomId,
		})
		if err != nil || memberInfo == nil {
			global.GVA_LOG.Error("查聊天室成员表异常", zap.Any("request", req), zap.Error(err))
			apireturn = ApiReturn.ErrSystem
			return apireturn
		}
		update := bson.D{{"$set", bson.M{
			"status": v,
		}}}
		filter := bson.M{"customerid": user.CustomerId, "roomid": req.RoomId}
		if _, err := mongodb.CommunicationRoomMemberCollection.UpdateOne(ctx, filter, update); err != nil {
			global.GVA_LOG.Error("修改用户聊天室成员信息异常", zap.Any("request", req), zap.Error(err))
			apireturn = ApiReturn.ErrSystem
			return apireturn
		}
	}
	apireturn = ApiReturn.OK
	return apireturn
}
